package com.seo.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.seo.service.user.sdk.UserService;

import lombok.extern.slf4j.Slf4j;

/**
 * NoDomainSecurityInterceptor
 * 
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
public class NoDomainSecurityInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		log.info("进入域名拦截器...");
		request.setAttribute("domainUserId", 147);
		Map<String, Object> user = userService.getUserById(147);
		
		String roleCode = (String) user.get("roleCode");
		boolean isCompany = false;
		String companyName = null;
		if ("proxy".equals(roleCode)) {
			companyName = (String) user.get("companyName");
			if (StringUtils.isNotEmpty(companyName)) {
				isCompany = true;
			}
		}
		if (!isCompany) {
			Integer parentId = (Integer) user.get("parentId");
			if (parentId != 0) {
				Map<String, Object> parentUser = userService.getUserById(parentId);
				if (parentUser != null) {
					roleCode = (String) parentUser.get("roleCode");
					if ("proxy".equals(roleCode)) {
						companyName = (String) parentUser.get("companyName");
						if (StringUtils.isNotEmpty(companyName)) {
							isCompany = true;
						}
					}
				}
			}

		}
		request.setAttribute("companyName", isCompany ? companyName : "金发仁");
		request.setAttribute("templet", user.get("templet"));
		return true;
	}


}
